<template>
  <div id="container" class="container"></div>
</template>
<script lang="ts" setup>
import { onMounted, watch } from "vue";
import loadScript from "@/utils/TMap";
declare const TMap: any;

const props = defineProps({
  address: {
    type: String,
    default: ""
  },
  lat: {
    type: Number,
    default: 37.870451
  },
  lng: {
    type: Number,
    default: 112.549656
  }
});
const emits = defineEmits(["getAddress", "getLatLng"]);
// 地图
let map: any, marker: any;
// 点坐标
watch(
  () => props.address,
  (newVal) => {
    getLatLng(newVal);
  }
);

// 初始化地图
async function initMap() {
  const center = new TMap.LatLng(props.lat, props.lng);
  const myOptions = {
    zoom: 16,
    center: center
  };
  map = new TMap.Map(document.getElementById("container"), myOptions);
  createMarker(center);
}

// 创建点标记
function createMarker(center: any) {
  console.log("center.....", center);
  marker = new TMap.MultiMarker({
    map: map,
    styles: {
      // 点标记样式
      marker: new TMap.MarkerStyle({
        width: 20, // 样式宽
        height: 30, // 样式高
        anchor: { x: 10, y: 30 } // 描点位置
      })
    },
    geometries: [
      // 点标记数据数组
      {
        // 标记位置(纬度，经度，高度)
        position: center,
        styleId: "marker"
      }
    ]
  });
  addMarker();
}

// 监听点击事件添加marker
function addMarker() {
  map.on("click", (evt: any) => {
    console.log("evt.....", evt);
    marker.add({
      position: evt.latLng,
      styleId: "marker"
    });
    const geocoder = new TMap.service.Geocoder();
    geocoder
      .getAddress({ location: new TMap.LatLng(evt.latLng.lat, evt.latLng.lng) })
      .then((res: any) => {
        console.log(res);
        if (res.status === 0) {
          emits("getLatLng", [evt.latLng.lat, evt.latLng.lng]);
          emits("getAddress", res.result.address);
        }
      });
  });
}

// 移除marker事件
function removeMarker() {
  if (marker) {
    console.log("......", marker);
    marker.setMap(null);
    marker = null;
  }
}

// 根据地址获取经纬度及点坐标
function getLatLng(address: string) {
  if (address && address.length > 0) {
    const geocoder = new TMap.service.Geocoder();
    console.log(geocoder, address);
    geocoder.getLocation({ address: address }).then((res: any) => {
      console.log(res);
      if (res.status === 0) {
        removeMarker();
        createMarker(new TMap.LatLng(res.result.location.lat, res.result.location.lng));
        updateMap(res.result.location.lat, res.result.location.lng);
        emits("getLatLng", [res.result.location.lat, res.result.location.lng]);
      }
    });
  }
}

function updateMap(markerLat: string, markerLng: string) {
  // 更新地图中心点
  map.setCenter(new TMap.LatLng(markerLat, markerLng));
}

onMounted(async () => {
  await loadScript();
  await initMap();
});
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 300px;
}
</style>
